﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using System.Collections;
using System.Windows;

namespace PDF_merger
{
    class MergeEx
    {
        #region Fields
        private string sourcefolder;
        private string firstFile;
        private string secondFile;
        private string destinationfile;
        private IList fileList = new ArrayList();
        #endregion

        #region Public Methods
        ///
        /// Add a new file, together with a given docname to the fileList and namelist collection
        ///
        public void AddFile(string pathnname)
        {
            fileList.Add(pathnname);
        }

        ///
        /// Generate the merged PDF
        ///
        public void Execute()
        {
            MergeDocs();
        }
        public void ExecuteTwo()
        {
            MergeDocs2();
        }
        #endregion

        #region Private Methods
        ///
        /// Merges the Docs and renders the destinationFile
        ///
        private void MergeDocs()
        {

            //Step 1: Create a Docuement-Object
            Document document = new Document();
            try
            {
                //Step 2: we create a writer that listens to the document
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationfile, FileMode.Create));

                //Step 3: Open the document
                document.Open();

                PdfContentByte cb = writer.DirectContent;
                PdfImportedPage page;

                int n = 0;
                int rotation = 0;

                //Loops for each file that has been listed
                foreach (string filename in fileList)
                {
                    //The current file path
                    string filePath = sourcefolder + filename;

                    // we create a reader for the document
                    PdfReader reader = new PdfReader(filePath);

                    //Gets the number of pages to process
                    n = reader.NumberOfPages;

                    int i = 0;
                    while (i < n)
                    {
                        i++;
                        document.SetPageSize(reader.GetPageSizeWithRotation(1));
                        document.NewPage();

                        //Insert to Destination on the first page
                        //if (i == 1)
                        //{
                        //    Chunk fileRef = new Chunk(" ");
                        //    fileRef.SetLocalDestination(filename);
                        //    document.Add(fileRef);
                        //}

                        page = writer.GetImportedPage(reader, i);
                        rotation = reader.GetPageRotation(i);
                        //cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                        if (rotation == 90 || rotation == 270)
                        {
                            cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                        }
                        else if (rotation == 180)
                        {
                            cb.AddTemplate(page, -1f, 0, 0, -1f,
                                                    reader.GetPageSizeWithRotation(i).Width,
                                                    reader.GetPageSizeWithRotation(i).Height);
                        }
                        else
                        {
                            cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                        }
                    }
                }
            }
            catch (Exception e) { throw e; }
            finally { document.Close(); }
        }




        private void MergeDocs2()
        {

            //Step 1: Create a Docuement-Object
            Document document = new Document();
            try
            {
                //Step 2: we create a writer that listens to the document
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationfile, FileMode.Create));

                //Step 3: Open the document
                document.Open();

                PdfContentByte cb = writer.DirectContent;
                PdfImportedPage page;

                int n = 0;
                int rotation = 0;

                //Loops for each file that has been listed

                //The current file path
                //string filePath = sourcefolder + filename;

                // we create a reader for the document
                PdfReader reader1 = new PdfReader(firstFile);
                PdfReader reader2 = new PdfReader(secondFile);
                //Gets the number of pages to process
                int n1 = reader1.NumberOfPages;
                int n2 = reader2.NumberOfPages;


                for (int i = 1; i < Math.Min(n1, n2) + 1; i++)
                {
                    page = AddPage(document, writer, cb, ref rotation, reader1, i);
                    page = AddPage(document, writer, cb, ref rotation, reader2, n2-i+1);
                }
                if (n1 > n2)
                {
                    page = AddPage(document, writer, cb, ref rotation, reader1, n1);
                }
                if (n1 < n2)
                {
                    page = AddPage(document, writer, cb, ref rotation, reader2, n2);
                }
                MessageBox.Show("Success!");

            }   
            catch (Exception e) {
                MessageBox.Show("Fail! + Error: " + e.Message); 
            }
            finally { document.Close(); }
        }

        private static PdfImportedPage AddPage(Document document, PdfWriter writer, PdfContentByte cb, ref int rotation, PdfReader reader1, int i)
        {
            PdfImportedPage page;
            document.SetPageSize(reader1.GetPageSizeWithRotation(1));
            document.NewPage();
            page = writer.GetImportedPage(reader1, i);
            rotation = reader1.GetPageRotation(i);
            if (rotation == 90 || rotation == 270)
            {
                cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader1.GetPageSizeWithRotation(i).Height);
            }
            else if (rotation == 180)
            {
                cb.AddTemplate(page, -1f, 0, 0, -1f,
                                        reader1.GetPageSizeWithRotation(i).Width,
                                        reader1.GetPageSizeWithRotation(i).Height);
            }
            else
            {
                cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
            }
            return page;
        }


        #endregion

        #region Properties
        ///
        /// Gets or Sets the SourceFolder
        ///
        public string SourceFolder
        {
            get { return sourcefolder; }
            set { sourcefolder = value; }
        }

        ///
        /// Gets or Sets the DestinationFile
        ///
        public string DestinationFile
        {
            get { return destinationfile; }
            set { destinationfile = value; }
        }

        public string FirstFile
        {
            get { return firstFile; }
            set { firstFile = value; }
        }
        public string SecondFile
        {
            get { return secondFile; }
            set { secondFile = value; }
        }
        #endregion
    }
}
